<template>
  <div class='container' ref="boxRef">
    <el-card>

      <!-- 卡片头部区域 -->
      <template #header>
        <span>{{QStitle}}</span>
      </template>

      <!-- 卡片表单区域 -->
      <el-form label-width="120px" :model="formData" :rules="rules" ref="formRef">
        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="formData.subjectID" @change="changeSubjectID">
            <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="formData.catalogID">
            <el-option v-for="item in directoryList" :key="item.id" :label="item.directoryName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="formData.enterpriseID">
            <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 + 地区 -->
        <el-form-item label="城市：" prop="city">
          <el-select v-model="formData.province" class="min-select" ref="cityRef" @change="changeP">
            <el-option v-for="item in provincesList" :key="item" :value="item"></el-option>
          </el-select>
          <el-select v-model="formData.city" class="min-select">
            <el-option v-for="item in citysList" :key="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="formData.direction">
            <el-option v-for="item in directionList" :key="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="formData.questionType">
            <el-radio :label="'1'">单选</el-radio>
            <el-radio :label="'2'">多选</el-radio>
            <el-radio :label="'3'">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="formData.difficulty">
            <el-radio :label="'1'">简单</el-radio>
            <el-radio :label="'2'">一般</el-radio>
            <el-radio :label="'3'">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干：" prop="question">
          <!-- 富文本编辑器 -->
          <quill-editor id="myQuillEditor" ref="myQuillEditor" :options="editorOption" v-model="formData.question" @blur="validateQS"></quill-editor>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项：" prop="options" v-if="QSType!=='3'">
          <div>
          <!-- 单选框 -->
           <el-radio-group v-model="radioData" @change="valueChange" v-if="QSType==='1'">
            <!-- 单选选项 -->
              <div v-for="item in formData.options" :key="item.code">
                <el-radio :label="item.code" class="changeRC">
                <span>{{item.code}}：</span>
                  <el-input class="radio-input" v-model="item.title"></el-input>
                  <el-upload
                  action="#"
                  :file-list="[]"
                  list-type="picture-card"
                  :http-request="upload"
                  :before-upload="handelBeforeUpload"
                  >
                    <span v-show="!item.img">上传图片</span>
                    <img v-if="item.img" :src="item.img" alt="" class="uploadImg">
                    <i class="el-icon-circle-close" @click.stop="deleteImg(item.code)"></i>
                  </el-upload>
                </el-radio>
              </div>
          </el-radio-group>
          <!-- 多选框 -->
          <el-checkbox-group v-model="checkboxData" v-else @change="changeCheckBox">
            <!-- 多选选项 -->
              <div v-for="item in formData.options" :key="item.code">
                <el-checkbox :label="item.code" class="changeRC">
                <span>{{item.code}}：</span>
                  <el-input class="radio-input" v-model="item.title"></el-input>
                  <el-upload
                  action="#"
                  :file-list="[]"
                  list-type="picture-card"
                  :http-request="upload"
                  :before-upload="handelBeforeUpload"
                  >
                    <span v-show="!item.img">上传图片</span>
                    <img v-if="item.img" :src="item.img" alt="" class="uploadImg">
                    <i class="el-icon-circle-close" @click.stop="deleteImg(item.code)"></i>
                  </el-upload>
                </el-checkbox>
              </div>
          </el-checkbox-group>
          </div>
          <!-- 按钮 -->
        <el-form-item><el-button  type="danger" size="small" :disabled="QSType!=='2'" @click="addOpt">+增加选项与答案</el-button></el-form-item>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频：" prop="videoURL">
          <el-input class="fourHundredipt" v-model="formData.videoURL"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item label="答案解析：" prop="answer">
          <!-- 富文本编辑器 -->
          <quill-editor id="myQuillEditor2" ref="myQuillEditor2" :options="editorOption" v-model="formData.answer" @blur="validateAnswer"></quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注：" prop="remarks">
          <el-input class="fourHundredipt" type="textarea" :rows="4" v-model="formData.remarks"></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签：" prop="tags">
          <!-- allow-create属性即可通过在输入框中输入文字来创建新的条目。注意此时filterable必须为真。 -->
          <el-select multiple allow-create filterable v-model="formDataTags" @change="changeTags">
            <el-option v-for="item in tagList" :key="item.id" :value="item.tagName"></el-option>
          </el-select>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="clickSubmit" v-if="QStitle==='试题录入'">确认提交</el-button>
          <el-button type="success" @click="clickSubmit" v-else>确认修改</el-button>
        </el-form-item>

      </el-form>

    </el-card>
  </div>
</template>

<script>
import { add as addQuestionNew, detail as detailById, update as updateById } from '@/api/hmmm/questions'
import { simple } from '@/api/hmmm/subjects'
import { list as companysList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { list as directorysList } from '@/api/hmmm/directorys'
import { list as tagsList } from '@/api/hmmm/tags'
// 富文本编辑器使用vue-quill-editor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 使用腾讯云服务器处理图片问题
const COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const cos = new COS({
  SecretId: 'AKIDvquS704AGrHersz33zpxFWTGtLanqkW7',
  SecretKey: 'YyTo5XtHWkw43qYBtTL5cNwZ7Xltrq0A'
})
// 定制toolbar---工具栏
// const toolbarOptions = [
//   ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
//   [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
//   ['blockquote'], // 引用 ---['blockquote']
//   ['code-block', 'image', 'link'] // 'code-block'-代码块 image - 图片 'link'-链接
// ]
const _EditorOption_ = function (pageThis) {
  return {
    modules: {
      toolbar: {
        container:
        [
          ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
          [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
          ['blockquote'], // 引用 ---['blockquote']
          ['code-block', 'image', 'link'] // 'code-block'-代码块 image - 图片 'link'-链接
        ],
        handlers: {
          image: function (value) {
            if (value) {
              // console.log(this)// 此时this是头部工具栏当前对象
              const parentIdStr = this.container.parentElement.id// 获取容器quill-editor标签的id
              let fileInput = this.container.querySelector('input.ql-image[type=file]')
              if (fileInput == null) {
                fileInput = document.createElement('input')
                fileInput.setAttribute('type', 'file')
                fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon')
                fileInput.classList.add('ql-image')
                fileInput.addEventListener('change', function () {
                  const files = fileInput.files// 获取文件
                  pageThis.QuillEditorImgUpload(parentIdStr, files)// 调取当前页面富文本图片上传的方法
                })
                this.container.appendChild(fileInput)
              }
              fileInput.click()
            } else {
              this.quill.format('image', false)
            }
          }
        }
      }
    }
  }
}

export default {
  name: 'questionNew',
  components: {
    quillEditor
  },
  data () {
    return {
      editorOption: _EditorOption_(this),
      imgList: [],
      directionList: direction, // 方向列表
      subjectList: [], // 学科列表
      companyList: [], // 企业列表
      provincesList: [], // 城市列表
      citysList: [], // 区域列表
      directoryList: [], // 目录列表
      tagList: [], // 试题标签列表---渲染用
      formDataTags: [], // 试题标签显示绑定项
      radioData: null, // 便于单选框绑定数据使用
      checkboxData: [], // 便于多选框绑定数据使用
      formData: {
        subjectID: null, // 学科---xyjy
        catalogID: null, // 目录---xyjy
        enterpriseID: null, // 企业---xyjy
        province: null, // 省份---xyjy
        city: null, // 城市---xyjy
        direction: null, // 方向---xyjy
        questionType: '1', // 题型---xyjy
        difficulty: '1', // 难度---xyjy
        question: null, // 题干---xyjy
        options: [// 选项数据
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ],
        videoURL: null, // 解析视频
        answer: null, // 答案解析---xyjy
        remarks: null, // 题目备注
        tags: null// 试题标签---此数据后端定义及返回的是字符串，多个数据也是以逗号隔开的字符串，但是饿了么文档中需要数组，注意转换数据
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: ['blur', 'change'] }],
        catalogID: [{ required: true, message: '请选择目录', trigger: ['blur', 'change'] }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: ['blur', 'change'] }],
        province: [{ required: true, message: '请选择地区', trigger: ['blur'] }],
        city: [{ required: true, message: '请选择地区', trigger: ['blur'] }],
        direction: [{ required: true, message: '请选择方向', trigger: ['blur', 'change'] }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        questionType: [{ required: true, message: '', trigger: ['blur', 'change'] }],
        difficulty: [{ required: true, message: '', trigger: ['blur', 'change'] }],
        tags: [{ required: true, message: '请选择标签', trigger: ['change'] }]
      }
    }
  },
  computed: {
    QSType () { // 题型改变依赖
      return this.formData.questionType
    },
    QStitle () { // 标题
      return this.$route.query?.id ? '试题修改' : '试题录入'
    }

  },
  async created () {
    this.getSimple()
    this.getCompanys()
    this.getProvinces()
    // if (this.QStitle === '试题录入') { this.resetForm() }
    if (this.QStitle === '试题修改') {
      await this.getDetailById()
      this.changeP()
      this.changeSubjectID()
      await this.getDetailById()
    }
  },
  methods: {
    // 修改页面数据回显之获得数据
    async getDetailById () {
      const id = this.$route.query?.id
      const { data } = await detailById({ id })
      this.formData = data

      // 回显单选/多选的数据
      const obj = this.formData.options.filter(item => item.isRight === 1)
      if (obj && this.QSType === '1') { obj.forEach(item => { this.radioData = item?.code }) }
      if (obj && this.QSType === '2') { obj.forEach(item => { this.checkboxData.push(item?.code) }) }
      // 回显试题标签的数据
      this.formDataTags = this.formData.tags?.split(',')
      // 解决富文本编辑器因为赋值导致自动获得焦点，页面无法处于顶部的问题
      this.$nextTick(() => {
        this.$refs.myQuillEditor.quill.enable(true)
        this.$refs.myQuillEditor.quill.blur()
        this.$refs.myQuillEditor2.quill.enable(true)
        this.$refs.myQuillEditor2.quill.blur()
        window.scrollTo(0, 0)
      })
    },
    // 重置表单
    resetForm () {
      this.formData = {
        subjectID: null, // 学科---xyjy
        catalogID: null, // 目录---xyjy
        enterpriseID: null, // 企业---xyjy
        province: null, // 省份---xyjy
        city: null, // 城市---xyjy
        direction: null, // 方向---xyjy
        questionType: '1', // 题型---xyjy
        difficulty: '1', // 难度---xyjy
        question: null, // 题干---xyjy
        options: [// 选项数据
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ],
        videoURL: null, // 解析视频
        answer: null, // 答案解析---xyjy
        remarks: null, // 题目备注
        tags: null// 试题标签---此数据后端定义及返回的是字符串，多个数据也是以逗号隔开的字符串，但是饿了么文档中需要数组，注意转换数据
      }
      this.radioData = null
      this.checkboxData = []
      this.formDataTags = []
      this.$refs.formRef.resetFields()
    },
    changeTags () {
      this.formData.tags = this.formDataTags.join(',')// 转换试题标签数据
    },
    // 确认提交
    clickSubmit () {
      this.$refs.formRef.validate(async flag => {
        if (!flag) return this.$message.warning('您还有数据未提交~')
        // 校验通过
        this.formData.tags = this.formDataTags.join(',')// 转换试题标签数据
        // this.formData.options.forEach(item => {
        //   if (!item.isRight) { item.img = ''; item.title = '' }// 如果选项没选，则其图片地址以及标题为空---不可取(此时都要上传)
        // })
        if (this.QStitle === '试题录入') {
          await addQuestionNew(this.formData)
          this.$message.success('添加成功')
        }
        if (this.QStitle === '试题修改') {
          await updateById(this.formData)
          this.$message.success('修改成功')
        }
        this.resetForm()
        this.$router.push('/questions/list')
      })
    },
    // 对部分表单字段进行校验的方法
    validateQS () {
      this.$refs.formRef.validateField('question')
    },
    validateAnswer () {
      this.$refs.formRef.validateField('answer')
    },
    // 增加选项
    addOpt () {
      const index = this.formData.options[this.formData.options.length - 1].code
      if (index === 'Z') {
        this.$message.warning('不能在添加啦~已经到底啦')
        return
      }
      this.formData.options.push({
        code: String.fromCharCode(index.charCodeAt(0) + 1),
        title: '',
        img: '',
        isRight: false
      })
    },
    // 城市数据变化，就会实时变化区域的渲染
    changeP () {
      this.formData.city = null
      this.getCitys(this.formData.province)
    },
    // 学科发生变化，实时渲染目录及试题标签列表
    changeSubjectID () {
      this.formData.catalogID = null
      this.formData.tags = null
      this.getDirectorysList({ subjectID: this.formData.subjectID })// 目录
      this.getTagsList({ subjectID: this.formData.subjectID })// 试题标签
    },
    // 获取试题标签列表(根据学科ID)
    async getTagsList (subjectID) {
      const { data: { items } } = await tagsList(subjectID)
      this.tagList = items
    },
    // 获取目录列表(根据学科ID)
    async getDirectorysList (subjectID) {
      const { data: { items } } = await directorysList(subjectID)
      this.directoryList = items
    },
    // 获取区域列表(根据城市)
    async getCitys (data) {
      const res = await citys(data)
      this.citysList = res
    },
    // 获取城市列表
    getProvinces () {
      const res = provinces()
      this.provincesList = res
    },
    // 获取企业列表
    async getCompanys () {
      const { data: { items } } = await companysList({ page: 1, pagesize: 100 })
      this.companyList = items
    },
    // 获取学科简单列表
    async getSimple () {
      const { data } = await simple()
      this.subjectList = data
    },
    // 选项表单中单选按钮值改变即会触发该事件
    valueChange (value) {
      this.formData.options.forEach(item => { item.isRight = false })
      this.formData.options.find(item => item.code === value).isRight = true
    },
    // 选项表单中多选按钮值改变即会触发该事件
    changeCheckBox (objV) {
      this.formData.options.forEach(item => { item.isRight = false })
      objV.forEach(checked => {
        this.formData.options.find(item => item.code === checked).isRight = true
      })
    },
    // 配置上传前的校验, 只要通过校验, 才能进行上传
    handelBeforeUpload (file) {
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    },
    // 点击上传组件右上角×---删除当前图片数据
    deleteImg (code) {
      if (this.QSType === '1') {
        setTimeout(() => { this.radioData = null }, 0)
      }
      if (this.QSType === '2') {
        setTimeout(() => { this.checkboxData.pop() }, 0)
      }
      this.formData.options.find(item => item.code === code).img = ''
    },
    // 自定义上传方法 上传到腾讯云---upload组件上传图片---单选多选点击上传头像的逻辑
    upload (params) {
      cos.putObject({
        Bucket: 'hrsass-104-1316404828', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        // Key: Date.now() + '_' + params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: params.file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        // 上传进度条
        onProgress: (progressData) => {
        }
      }, (err, data) => {
        if (err)console.log(err)// 这里必须处理err和data，否则就会报错
        if (data && data.statusCode === 200) {
          if (this.QSType === '1') {
            if (this.radioData) {
              this.formData.options.find(item => item.code === this.radioData).img = 'https://' + data.Location
              this.radioData = null
            }
          }
          if (this.QSType === '2') {
            const lastone = this.checkboxData.length - 1
            if (lastone >= 0) {
              this.formData.options.find(item => item.code === this.checkboxData[lastone]).img = 'https://' + data.Location
              this.checkboxData = []
            }
          }
        }
      })
    }, // 自定义上传方法 上传到腾讯云---upload组件上传图片---富文本工具栏点击图片处理问题

    // 富文本- 图片上传
    QuillEditorImgUpload (domId, files) {
      // 此时可以自行将文件上传至服务器
      cos.putObject({
        Bucket: 'hrsass-104-1316404828', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        // Key: Date.now() + '_' + params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Key: files[0].name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: files[0], /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        // 上传进度条
        onProgress: (progressData) => {
        }
      }, (err, data) => {
        if (err)console.log(err)// 这里必须处理err和data，否则就会报错
        // 获取富文本组件实例
        if (data && data.statusCode === 200) {
          const imageUrl = 'https://' + data.Location// 拼接图片地址
          let quill = ''// 获取富文本编辑器dom对象
          switch (domId) {
            case 'myQuillEditor':// 活动介绍
              quill = this.$refs.myQuillEditor.quill
              break
            case 'myQuillEditor2':// 场馆介绍
              quill = this.$refs.myQuillEditor2.quill
              break
            default:
              break
          }
          const length = quill.getSelection().index// 获取光标所在位置
          quill.insertEmbed(length, 'image', imageUrl)// 插入图片
          quill.setSelection(length + 1)// 调整光标到最后
        } else {
          this.$message.error('图片插入失败')
        }
      })
    }
  },
  watch: {
    QSType (newV, oldV) {
      if (newV !== oldV) {
        this.radioData = null
        this.checkboxData = []
        this.formData.options.forEach(item => {
          item.isRight = false
          item.title = ''
          item.img = ''
        })
      }
    },
    QStitle (newV) { // 从其他页面点击修改过来后，再点击当前侧边栏的试题录入时，清空表单内容
      if (newV === '试题录入') { this.resetForm() }
    }
  }
}
</script>

<style scoped lang='scss'>
.container{
  padding: 20px 20px;
  .quill-editor{
    ::v-deep{
      .ql-toolbar{
      padding: 0 8px;
      height: 38px;
      line-height: 38px;
      }
      .ql-editor{
        height: 200px;
      }
    }
  }
  ::v-deep{
    // 富文本placeholder
    .ql-editor.ql-blank::before{
      content: '';
    }
  }
  .fourHundredipt{
    width: 400px;
  }
  .el-select{
    width: 400px;
  }
  .radio-div{
    height: 80px;
  }
  ::v-deep{
    .radio-input{
      width: 240px;
    }
    .min-select{
      width: 197.5px;
      margin-right: 5px;
    }
    .changeRC{
      position: relative;
      margin: 10px 0 40px;
    }
    .el-upload--picture-card{
      width: 100px;
      height: 60px;
      position: absolute;
      left: 300px;
      top: -14px;
      span{
        color: black;
        position: absolute;
        width: 0px;
        height: 0px;
        left: 20px;
        top: -43px;
      }
      i{
        position: absolute;
        background-color: #fff;
        font-size: 20px;
        top: -10px;
        right: -10px;
      }
    }
  }
  ::v-deep{//这个deep内的解决upload上传恶心的动画+图片突然变大显示的问题
  .el-upload-list__item {
  transition: none !important;//去除upload的上传动画
  }
  .el-upload-list__item-thumbnail {
    /* 图片在方框内显示长边 */
    object-fit: scale-down !important;
  }
  .el-upload-list--picture-card{
    display: none !important;
  }
  }
  .uploadImg{
    width:94px;
    height:58px;
    position:absolute;
    top:0px;
    left:2px
  }
}
</style>
